<template>
  <div class="notice-container">
    <!-- 左侧导航 -->
    <el-menu
        default-active="1"
        class="el-menu-vertical-demo"
        @select="handleMenuSelect"
        background-color="#1f2126"
        text-color="#bfc3c9"
        active-text-color="#409eff"
    >
      <el-menu-item index="1">
        <i class="el-icon-at"></i>
        <span>通知</span>
        <span v-if="noticeCounts.all > 0" class="badge">{{ noticeCounts.all }}</span>
      </el-menu-item>
      <el-menu-item index="2">
        <i class="el-icon-chat-dot-round"></i>
        <span>点赞</span>
        <span v-if="noticeCounts.like > 0" class="badge">{{ noticeCounts.like }}</span>
      </el-menu-item>
      <el-menu-item index="3">
        <i class="el-icon-star-on"></i>
        <span>评论</span>
        <span v-if="noticeCounts.comment > 0" class="badge">{{ noticeCounts.comment }}</span>
      </el-menu-item>
      <el-menu-item index="4">
        <i class="el-icon-message"></i>
        <span>收藏</span>
        <span v-if="noticeCounts.collection > 0" class="badge">{{ noticeCounts.collection }}</span>
      </el-menu-item>
      <el-menu-item index="5">
        <i class="el-icon-bell"></i>
        <span>关注</span>
        <span v-if="noticeCounts.follow > 0" class="badge">{{ noticeCounts.follow }}</span>
      </el-menu-item>
      <el-menu-item index="6">
        <i class="el-icon-bell"></i>
        <span>私信</span>
        <span v-if="noticeCounts.message > 0" class="badge">{{ noticeCounts.message }}</span>
      </el-menu-item>
    </el-menu>
    <!-- 右侧内容区域 -->
    <div class="content-wrapper">
      <div class="notice-card-list">
        <NoticeCard
            v-for="item in filteredNotices"
            :key="item.id"
            :notice="item"
            @delete="handleDelete"
            @viewDetail="openDetail"
        />
      </div>
      <!-- 抽屉组件 -->
      <NoticeDetailDrawer ref="detailDrawer" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import NoticeCard from './NoticeCard.vue'
import NoticeDetailDrawer from './NoticeDetailDrawer.vue'

import { useUserStore } from '@/stores/user' // 引入用户状态管理

const userStore = useUserStore()
const userId = ref(userStore.id) // 获取当前登录用户ID

// 创建对抽屉组件的引用
const detailDrawer = ref(null)

// 打开详情抽屉并标记通知为已读
const openDetail = async (notice) => {
  try {
    if (notice.type === 'comment') {
      const { data } = await axios.get(`/api/notice/comment/${notice.id}`)
      notice.commentText = data.commentText
    }
    // 确保抽屉组件已正确引用
    if (detailDrawer.value) {
      detailDrawer.value.handleDetailData(notice)

      // 如果通知未读，标记为已读
      if (!notice.isRead) {
        await markNoticeAsRead(notice.id)
        notice.isRead = true
        updateNoticeCounts()
      }
    }
  } catch (error) {
    ElMessage.error('获取通知详情失败，请稍后重试')
    console.error('获取通知详情失败:', error)
  }
}

// 分类激活标识，对应左侧 menu 的 index
const activeTab = ref('1')
// 通知数据
const noticeData = ref([])
// 各类通知的未读计数
const noticeCounts = ref({
  all: 0,
  like: 0,
  comment: 0,
  collection: 0,
  follow: 0,
  message: 0
})

/**
 * 获取通知数据和未读计数
 * @param tab 分类标识，不同分类可传不同参数给接口区分
 */
const fetchData = async (tab: string) => {
  try {
    // 并行请求通知列表和未读计数
    const [noticesRes, countsRes] = await Promise.all([
      axios.get('/api/notice', { params: { userId: userId.value } }),
      axios.get('/api/notice/unread-counts', { params: { userId: userId.value } })
    ])

    // 更新通知数据
    noticeData.value = noticesRes.data.sort((a, b) =>
        new Date(b.time).getTime() - new Date(a.time).getTime()
    )

    // 更新未读计数
    noticeCounts.value = countsRes.data || {
      all: 0,
      like: 0,
      comment: 0,
      collection: 0,
      follow: 0,
      message: 0
    }

    console.log('获取通知数据成功:', noticeData.value)
    console.log('获取未读计数成功:', noticeCounts.value)
  } catch (error) {
    ElMessage.error('获取通知数据失败，请稍后重试')
    console.error('获取通知数据失败:', error)
  }
}

// 根据当前标签过滤的通知列表
const filteredNotices = computed(() => {
  if (activeTab.value === '1') {
    return noticeData.value // 全部通知
  }

  const typeMap = {
    '2': 'like',
    '3': 'comment',
    '4': 'collection',
    '5': 'follow',
    '6': 'message'
  }

  const targetType = typeMap[activeTab.value]
  if (!targetType) return noticeData.value

  return noticeData.value.filter(notice => notice.type === targetType)
})

// 更新未读计数
const updateNoticeCounts = () => {
  const counts = {
    all: 0,
    like: 0,
    comment: 0,
    collection: 0,
    follow: 0,
    message: 0
  }

  noticeData.value.forEach(notice => {
    if (!notice.isRead) {
      counts.all++
      counts[notice.type] = (counts[notice.type] || 0) + 1
    }
  })

  noticeCounts.value = counts
  console.log('更新后的未读计数:', counts)
}

/**
 * 删除通知
 * @param id 通知ID
 */
const handleDelete = async (id: string) => {
  try {
    const { data } = await axios.delete(`/api/notice/${id}`)
    if (data > 0) {
      ElMessage.success('删除成功')
      // 重新获取当前分类数据
      fetchData(activeTab.value)
    }
  } catch (error) {
    ElMessage.error('删除失败，请稍后重试')
    console.error('删除通知失败:', error)
  }
}

/**
 * 切换左侧分类
 * @param key 分类标识，对应 menu 的 index
 */
const handleMenuSelect = (key: string) => {
  activeTab.value = key
  // 切换分类时重新请求数据
  fetchData(key)
}

// 标记通知为已读
const markNoticeAsRead = async (noticeId: string) => {
  try {
    await axios.put(`/api/notice/${noticeId}/read`)
    console.log('通知已标记为已读:', noticeId)
    // 更新本地数据中的通知状态
    const noticeIndex = noticeData.value.findIndex(n => n.id === noticeId)
    if (noticeIndex !== -1) {
      noticeData.value[noticeIndex].isRead = true
    }
  } catch (error) {
    console.error('标记通知为已读失败:', error)
  }
}

// 组件挂载时，检查用户是否已登录
onMounted(() => {
  if (!userId.value) {
    ElMessage.warning('请先登录以查看通知')
    // 可以在这里添加跳转到登录页面的逻辑
    return
  }
  fetchData(activeTab.value)
})

// 监听通知数据变化，更新未读计数
watch(noticeData, () => {
  updateNoticeCounts()
})
</script>


<style scoped>
.notice-container {
  display: flex;
  height: calc(100vh - 60px); /* 可根据实际布局调整高度 */
  background-color: #fff; /* 深色背景，适配示例界面 */
  color: #fff;
}

/* 左侧菜单样式 */
.el-menu-vertical-demo {
  border-right: none; /* 去掉默认边框 */
  background-color: #fff;
}

.el-menu-item {
  color: #bfc3c9;
}

.el-menu-item.is-active {
  color: #409eff;
}

/* 右侧内容区域 */
.content-wrapper {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 暂无内容提示 */
.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-tip i {
  margin-right: 8px;
  font-size: 24px;
  color: #666;
}

/* 通知卡片列表 */
.notice-card-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}
</style>